package com.shop.loan.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class ConsoleUtil {

    private static Logger logger = LoggerFactory.getLogger(ConsoleUtil.class);

//    public static void executeNewFlowByOne(String command) {
//        try {
//            Process p = Runtime.getRuntime().exec(command);
//            //用于处理Runtime.getRuntime().exec产生的错误流及输出流 ,防止阻塞
//            StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR");
//            errorGobbler.start();
//            StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(), "STDOUT");
//            outGobbler.start();
//            p.waitFor();
//        } catch (Exception e) {
//            e.printStackTrace();
//            logger.error(Util.GetErrorDetails(e));
//        }
//
//
////        List<String> commands = new ArrayList<>();
////        commands.add(command);
////        List<String> resultList = executeNewFlow(commands);
////        if (resultList != null && resultList.size() > 0) {
////            return resultList.get(0);
////        }
////        return null;
//    }

    public static List<String> executeNewFlow(List<String> commands) {
        List<String> rspList = new ArrayList<String>();
        BufferedReader in = null;
        PrintWriter out = null;
        Process proc = null;
        try {
            Runtime run = Runtime.getRuntime();
            proc = run.exec("/bin/bash", null, null);
            in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            for (String line : commands) {
                out.println(line);
            }
            out.println("exit");// 这个命令必须执行，否则in流不结束。
            String rspLine = "";
            while ((rspLine = in.readLine()) != null) {
                rspList.add(rspLine);
            }
            int procStatus = proc.waitFor();
            logger.info("procStatus：{}", procStatus);
        } catch (Exception e1) {
            e1.printStackTrace();
            logger.error(Util.GetErrorDetails(e1));
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
                if (proc != null) {
                    proc.destroy();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return rspList;
    }

}
